/**
 * 应用状态管理 - 使用Zustand
 */

import { create } from 'zustand';
import { AppState, AppActions, UploadFile, ProcessProgress, LanguageFile, DetectionReport, GeneratedFile } from '../types';

// 初始状态
const initialState: AppState = {
  uploadFile: null,
  isUploading: false,
  processProgress: {
    status: 'idle',
    progress: 0,
    message: '准备就绪',
  },
  languageFiles: [],
  detectionReport: null,
  generatedFiles: [],
  currentStep: 0,
  isProcessing: false,
};

// 创建状态管理
export const useAppStore = create<AppState & AppActions>((set) => ({
  ...initialState,

  // 文件上传相关
  setUploadFile: (file: UploadFile | null) => {
    set({ uploadFile: file });
  },

  setIsUploading: (isUploading: boolean) => {
    set({ isUploading });
  },

  // 处理进度相关
  setProcessProgress: (progress: ProcessProgress) => {
    set({ processProgress: progress });
  },

  // 语言数据相关
  setLanguageFiles: (files: LanguageFile[]) => {
    set({ languageFiles: files });
  },

  // 检测结果相关
  setDetectionReport: (report: DetectionReport | null) => {
    set({ detectionReport: report });
  },

  // 生成的文件相关
  setGeneratedFiles: (files: GeneratedFile[]) => {
    set({ generatedFiles: files });
  },

  // UI状态相关
  setCurrentStep: (step: number) => {
    set({ currentStep: step });
  },

  setIsProcessing: (isProcessing: boolean) => {
    set({ isProcessing });
  },

  // 更新单个语言文件
  updateLanguageFile: (languageCode: string, updatedData: Record<string, string>) => {
    set((state) => ({
      languageFiles: state.languageFiles.map(file => 
        file.code === languageCode 
          ? { ...file, data: updatedData }
          : file
      )
    }));
  },

  // 重置应用状态
  resetApp: () => {
    set(initialState);
  },
}));

// 选择器 - 用于优化性能
export const useUploadState = () => useAppStore((state) => ({
  uploadFile: state.uploadFile,
  isUploading: state.isUploading,
  setUploadFile: state.setUploadFile,
  setIsUploading: state.setIsUploading,
}));

export const useProcessState = () => useAppStore((state) => ({
  processProgress: state.processProgress,
  isProcessing: state.isProcessing,
  setProcessProgress: state.setProcessProgress,
  setIsProcessing: state.setIsProcessing,
}));

export const useLanguageState = () => useAppStore((state) => ({
  languageFiles: state.languageFiles,
  detectionReport: state.detectionReport,
  generatedFiles: state.generatedFiles,
  setLanguageFiles: state.setLanguageFiles,
  setDetectionReport: state.setDetectionReport,
  setGeneratedFiles: state.setGeneratedFiles,
  updateLanguageFile: state.updateLanguageFile,
}));

export const useUIState = () => useAppStore((state) => ({
  currentStep: state.currentStep,
  setCurrentStep: state.setCurrentStep,
}));
